package com.qf.air.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author 10537
 * @version V1.0
 * @Date 2021/11/12 20:12
 */
@Component
public class DynamicRouteFilter extends ZuulFilter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        // 推荐采用常量中提供的过滤器顺序进行加，减操作设置顺序
        // PRE_DECORATION_FILTER_ORDER = 5，是Zuul自带的前缀过滤器的最后一个过滤器
        return FilterConstants.PRE_DECORATION_FILTER_ORDER+2000;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext=RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String route = request.getParameter("route");
        if (!StringUtils.isEmpty(route)){
            Map<Object,Object>map=stringRedisTemplate.opsForHash().entries(route);
            if (map!=null&&map.size()>0){
                System.out.println(map);
                requestContext.put(FilterConstants.SERVICE_ID_KEY,map.get("serviceId"));
                requestContext.put(FilterConstants.REQUEST_URI_KEY,map.get("requestURI"));
            }
        }
        return null;
    }
}
